#define _BSD_SOURCE
#include <CODEPORTS/keyboard.h>
#include "codeports.h"
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>

void
KEY_Init(void)
{
	if((input.keyboard = open("/dev/keyboard", O_RDONLY)) == -1)
	{
		perror("Error: Unable to open keyboard device /dev/keyboard");
		exit(1);
	}

	tcgetattr(STDIN_FILENO, &input.mode.keyboard.original);
	input.mode.keyboard.current.c_lflag &= ~(ICANON | ISIG | IEXTEN | ECHO);
	input.mode.keyboard.current.c_iflag &= ~(BRKINT | ICRNL | IGNBRK | IGNCR | INLCR | INPCK | ISTRIP | IXON | PARMRK);
	input.mode.keyboard.current.c_oflag &= ~OPOST;
	input.mode.keyboard.current.c_cc[VMIN] = 1;
	input.mode.keyboard.current.c_cc[VTIME] = 0;
	tcsetattr(STDIN_FILENO, TCSAFLUSH, &input.mode.keyboard.current);

	fcntl(input.keyboard, F_SETFL, fcntl(input.keyboard, F_GETFL) | O_NONBLOCK);

	usleep(100000);
	while(read(input.keyboard, &input.mode.keyboard.event, sizeof(struct input_event)) == sizeof(struct input_event));
}

void
KEY_Final(void)
{
	close(input.keyboard);
	tcsetattr(STDIN_FILENO, TCSAFLUSH, &input.mode.keyboard.original);
}

int
KEY_Update(void)
{
	return read(input.keyboard, &input.mode.keyboard.event, sizeof(struct input_event)) == sizeof(struct input_event) ? input.mode.keyboard.event.code : 0;
}
